Home:ALL Converter>How to call model method in django view?

How to call model method in django view?

Ask Time:2020-06-23T02:04:48         Author:winston

Json Formatter

I'm trying to call a method in my Conversation model to get the latest message in my template. Here's my model.py:

from django.db import models
from django.contrib.auth.models import User

class Conversation(models.Model):
    participants = models.ManyToManyField(User)

    def get_last_message(self):
        lastmessage = Message.objects.filter(conversation=self).order_by('id')[0]

        return lastmessage


class Message(models.Model):
    sender = models.ForeignKey(User, on_delete= models.CASCADE, related_name="sender")
    recipient = models.ForeignKey(User, on_delete= models.CASCADE, related_name="recipient")
    text = models.TextField(null=False, blank=False)
    timestamp = models.DateTimeField(auto_now_add=True)
    conversation = models.ForeignKey(Conversation, blank=False, null=False, on_delete=models.CASCADE)

    def __str__(self):
        return self.text

And here is my template:

  {% for conversation in conversations %}
        <p>{{ conversation.get_latest_message.text }}</p>

I don't see any errors but there isn't any output. I can display the conversation.participants fine, but the call to the get_latest_message method doesn't do anything.

What am I missing?

Thanks!

Author:winston,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/62520727/how-to-call-model-method-in-django-view
yy